package cool.houge.pig.util;

import com.google.common.base.Strings;
import javax.annotation.Nonnull;
import org.springframework.web.reactive.function.server.ServerRequest;

/**
 * Web 工具类.
 *
 * @author KK (kzou227@qq.com)
 */
public class ServerRequestUtils {

  /**
   * @param request
   * @param name
   * @return
   */
  public static @Nonnull String requiredQueryString(ServerRequest request, String name) {
    return request
        .queryParam(name)
        .orElseThrow(
            () -> {
              String message =
                  Strings.lenientFormat("%s %s", request.methodName(), request.requestPath());
              return new MissingQueryParameterException(message, name);
            });
  }

  /**
   * @param request
   * @param name
   * @return
   */
  public static boolean requiredQueryBoolean(ServerRequest request, String name) {
    String v = requiredQueryString(request, name);
    return "1".equals(v) || Boolean.parseBoolean(v);
  }

  /**
   * @param request
   * @param name
   * @return
   */
  public static int requiredQueryInt(ServerRequest request, String name) {
    String v = requiredQueryString(request, name);
    try {
      return Integer.parseInt(v);
    } catch (NumberFormatException e) {
      String message = Strings.lenientFormat("%s %s", request.methodName(), request.requestPath());
      throw new WrongTypeQueryParameterException(message, name, v);
    }
  }

  /**
   * @param request
   * @param name
   * @return
   */
  public static long requiredQueryLong(ServerRequest request, String name) {
    String v = requiredQueryString(request, name);
    try {
      return Long.parseLong(v);
    } catch (NumberFormatException e) {
      String message = Strings.lenientFormat("%s %s", request.methodName(), request.requestPath());
      throw new WrongTypeQueryParameterException(message, name, v);
    }
  }

  /**
   * @param request
   * @param name
   * @return
   */
  public static double requiredQueryDouble(ServerRequest request, String name) {
    String v = requiredQueryString(request, name);
    try {
      return Double.parseDouble(v);
    } catch (NumberFormatException e) {
      String message = Strings.lenientFormat("%s %s", request.methodName(), request.requestPath());
      throw new WrongTypeQueryParameterException(message, name, v);
    }
  }
}
